package com.yisu.expressway.onedollar.presenter.impl;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.RecentAnnouncedItem;
import com.yisu.expressway.onedollar.model.RecentAnnouncedObj;
import com.yisu.expressway.onedollar.presenter.IRecentAnnouncedListPresenter;
import com.yisu.expressway.onedollar.view.IRecentAnnouncedListView;

import android.content.Context;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kaven on 2016/12/7.
 */

public class RecentAnnouncedListPresenterImpl implements IRecentAnnouncedListPresenter {
	private Context mContext;
	private IRecentAnnouncedListView mView;
	private RecentAnnouncedObj mRecentAnnouncedObj;
	public RecentAnnouncedListPresenterImpl(Context context, IRecentAnnouncedListView iRecentAnnouncedListView) {
		mContext = context;
		mView = iRecentAnnouncedListView;
	}

	@Override
	public void init() {
		//TODO
	}

	@Override
	public void fetchMore(int start, int pageSize) {
		fetchRecentAnnouncedList(start,pageSize);
	}

	@Override
	public List<RecentAnnouncedItem> getRecentAnnouncedList() {
		return mRecentAnnouncedObj == null ? null : mRecentAnnouncedObj.salesGoods;
	}


	@Override
	public String getSystemTime() {
		return mRecentAnnouncedObj == null ? null : mRecentAnnouncedObj.currentSystemTime;
	}
	private void fetchRecentAnnouncedList(int start, int pageSize) {
		if (pageSize <= 0){
			return;
		}
		Map<String, Object> params = new HashMap();

		int pageIndex = getPageIndex(start,pageSize);

		params.put("pageindex", pageIndex);
		params.put("pagesize", pageSize);
		ApiClientHelper.postApi(ApiSetting.getRecentlyAnnounced(), new TypeToken<RecentAnnouncedObj>() {
		}, new JSONObject(params), new Response.Listener<ApiResult<RecentAnnouncedObj>>() {
			@Override
			public void onResponse(ApiResult<RecentAnnouncedObj> result) {
				if (!result.success) {
					mView.showToast(result.getMsg());
					return;
				}
				mRecentAnnouncedObj = result.getResult();
				mView.refreshViews(true,null);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {
				mView.showToast(volleyError.getMessage());
				mView.refreshViews(true,volleyError.getMessage());
			}
		}, mContext);
	}

	private int getPageIndex(int start, int pageSize) {
		int round = start / pageSize;

		return round+1;
	}
}
